
package com.example.testutil.util;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

public class LruCacheUtils {

    private int MAXMEMONRY = (int) (Runtime.getRuntime().maxMemory() / 1024);

    private LruCache<String, Bitmap> mMemoryCache;

    public LruCacheUtils() {

        if (mMemoryCache == null) {
            mMemoryCache = new LruCache<String, Bitmap>(MAXMEMONRY / 8) {
                @Override
                protected int sizeOf(String key, Bitmap value) {
                    // 返回图片大小.
                    return value.getRowBytes() * value.getHeight() * 1024;
                }

                @Override
                protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
                    super.entryRemoved(evicted, key, oldValue, newValue);
                }
            };
        }
    }
  /*
   * 清理内存
   */
    public void clearCache() {
        if (mMemoryCache != null) {
            if (mMemoryCache.size() > 0) {
                LogUtil.d("mMemoryCache.size() -----------" + mMemoryCache.size());
                mMemoryCache.evictAll();
                LogUtil.d("mMemoryCache.size() -----------" + mMemoryCache.size());
            }
            mMemoryCache = null;
        }
    }
   /*
    * 添加图片到内存中去
    */
    public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (mMemoryCache.get(key) != null) {
            if (key != null && bitmap != null) {
                mMemoryCache.put(key, bitmap);
            }
        }
    }
 /*
  * 从内存中读取图片
  */
    public synchronized Bitmap getBitmapFromMemCache(String key) {

        Bitmap mBitmap = mMemoryCache.get(key);

        return mBitmap;
    }
    /*
     * 从内存中删除图片.
     */
    public synchronized void removeImageCache(String key) {
        if (mMemoryCache != null) {
            Bitmap bitmap = mMemoryCache.remove(key);
            if (bitmap != null) {
                bitmap.recycle();
            }
        }
    }
}
